package com.haiyou.dc.quartz.schedule;

import com.haiyou.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.Set;

@Slf4j
public class SchedulerExecJob implements Job {


    @Override
    public void execute(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        log.info("------------------>jobName={}", jobName);
        switch (jobName) {
            /*每5s执行一次*/
            case "quartz_test1":
                log.info("{} {} ====>quartz_test1<====", getAddress(), DateUtil.dateFormat());
                break;
            /*每5s执行一次*/
            case "quartz_test2":
                log.info("{} {} ====>quartz_test2<====", getAddress(), DateUtil.dateFormat());
                break;
            /*每5s执行一次*/
            case "quartz_test3":
                log.info("{} {} ====>quartz_test3<====", getAddress(), DateUtil.dateFormat());
                break;
            default:
                log.error("{} {} ====>other task<====", getAddress(), DateUtil.dateFormat());
                break;
        }
    }


    public String getAddress() {
        return "http://localhost:" + getLocalPort();
    }

    /**
     * 获取当前机器的端口号
     */
    public String getLocalPort() {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = null;
        try {
            objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        String port = objectNames.iterator().next().getKeyProperty("port");
        return port;
    }

}
